package com.zyj.dynds.interceptor;

import java.util.Properties;

import com.zyj.dynds.component.DynamicDataSourceHolder;
import com.zyj.dynds.consts.DataSourceKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * Mybatis拦截器：在执行SQL语句之前根据SQL语句类型选择数据源
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})})
public class DynamicDataSourceInterceptor implements Interceptor {

    /**
     * 核心方法：根据SQL的类型来选择使用master还是slave
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        boolean synchronizationActive = TransactionSynchronizationManager.isActualTransactionActive();
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        // 默认数据源为 Master
        DataSourceKey lookupKey = DynamicDataSourceHolder.DB_MASTER;
        if (!synchronizationActive) {
            // 判断当前SQL是否为 SELECT 类型
            if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
                lookupKey = DynamicDataSourceHolder.DB_SLAVE;
            }
        }
        DynamicDataSourceHolder.setDataSourceKey(lookupKey);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
